#pragma once
#include <iostream>
#include <string>
#include <functional>
#include <unordered_map>
#include "TcpServer.hpp"
#include "HttpProtocol.hpp"

using namespace TcpServerModule;
const std::string BlankLine = "\r\n";
//定义交互的方法类型
using http_handler_t = std::function<void(HttpRequest&, HttpResponse &)>;


class HttpServer
{
public:
    HttpServer(int port)
        : _tsvr(std::make_unique<TcpServer>(port))
    {
    }

    //内置交互方法
    void Resgiter(std::string funcname, http_handler_t func)
    {
        _route[funcname] = func;
    }

    //检查有没有此交互方法
    bool SafeCheck(const std::string &service)
    {
        auto iter = _route.find(service);
        return iter != _route.end();
    }

    void Start()
    {
        _tsvr->InitServer([this](SockPtr sockfd, InetAddr client)
                          { return this->HandlerHttpRequest(sockfd, client); });
        _tsvr->Loop();
    }

    // 就是我们处理的http的入口
    bool HandlerHttpRequest(SockPtr sockfd, InetAddr client)
    {
        LOG(LogLevel::DEBUG) << "HttpServer: get a new client: " << sockfd->Fd() << "addr info: " << client.Addr();
        std::string http_request; // 获取别人发送的http请求
        sockfd->Recv(&http_request);
        //std::cout << http_request << std::endl; // 在控制台打印出来看看字节流的请求

        // std::string status_line = "HTTP/1.1 200 OK" + Sep + BlankLine;

        // std::string body = "<!DOCTYPE html>\
        //                     <html>\
        //                    <head>\
        //                    <meta charset = \"UTF-8\">\
        //                    <title>hello world</title>\
        //                    </head>\
        //                    <body>\
        //                    <p> hellowrold</ p>\
        //                    </body> </html>";
        // std::string httpresponse = status_line + body;
        // sockfd->Send(httpresponse);
        // LOG(LogLevel::DEBUG) << " sucess ";

        // HttpRequest req;
        // req.Deserialize(http_request); //请求反序列化
        // HttpResponse resp;
        // resp.Build(req);
        // std::string resp_str ;
        // resp.Serialize(&resp_str);
        // sockfd->Send(resp_str);
        
        HttpRequest req;
        req.Deserialize(http_request);
        HttpResponse resp;
        //我们还需要判断是静态请求, 还是动态交互, 是否含有参数
        if(req.IsHasArgs())
        {
            std::cout << "IsHasArgs()" << std::endl;
            //2.提交参数
            std::string service = req.Path();
            if(SafeCheck(service))
                _route[req.Path()](req,resp);
            else
                resp.Build(req);
        }
        else
        {
            std::cout << "-----Non IsHasArgs()" << std::endl;
            resp.Build(req);
        }
        std::string resp_str;
        resp.Serialize(&resp_str);
        sockfd->Send(resp_str);
        return true;
    }

private:
    std::unique_ptr<TcpServer> _tsvr;
    std::unordered_map<std::string, http_handler_t> _route; //定义各种各样的交互方法
};
